<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */
declare (strict_types=1);

namespace app\madmin\service;

use app\madmin\model\MembershipLevel as admin;
use app\madmin\model\MembershipLevelContent AS content;
use app\madmin\model\MembershipLevelContentRelation;
use app\madmin\model\User;
use app\utils\RedisUtil;
use app\utils\TrimData;
use think\Exception;
use think\facade\Db;

class MembershipLevelService
{

    /**
     * 查询列表
     * @param int $page
     * @param int $size
     * @param array $data
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function findAll(array $data, int $page = 1, int $size = 10)
    {

        $admin = admin::field("*");
        $admin = TrimData::searchDataTrim($admin, $data, ['name', 'title']);

        //xxxxxxxx
        //xxxxx
        //xxxx
        $list = $admin->where($data)
            ->with(['content'])
            ->order('level', 'asc')
            ->order('status', 'desc')
            ->paginate(['page' => $page, 'list_rows' => $size]);
        return [HTTP_SUCCESS, $list];
    }

    /**
     * 保存数据
     * @param array $data
     * @return array
     */
    public function save(array $data)
    {
        $content_id = [];
        if (isset($data['status']) && $data['status'] == 1) {
            admin::update(['status' => 0], ['level' => $data['level']]);
        }
        if (!empty($data['content_id'])){
            $content_id = $data['content_id'];
            unset($data['content_id']);
        }
        $count = admin::where('level',$data['level'])->count();
        if ($count > 0)
            throw new Exception('已经存在该等级的数据',HTTP_NOTACCEPT);
        $admin = admin::create($data);
        foreach($content_id AS $key => $value){
            $array[] = ['mid' => $admin->id,'cid' => $value];
        }
        !empty($array) && (new MembershipLevelContentRelation)->insertAll($array);
        return [HTTP_CREATED, $admin];
    }

    /**
     * 读取一条数据
     * @param int $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function read(int $id)
    {
        $model = admin::with(['content'])
            ->find($id)
            ->hidden(['delete_time']);
        return [HTTP_SUCCESS, $model];
    }


    /**
     * 更新数据
     * @param int $id
     * @param array $data
     * @return array
     */
    public function update(int $id, array $data)
    {
        $content_id = [];
        $update_time = $data['update_time'];
        unset($data['update_time']);
        $model = admin::where(['update_time' => $update_time, 'id' => $id])->lock(true)->find();
        if (!$model) {
            return [HTTP_CREATED, 0];
        }

        if (isset($data['status']) && $data['status'] === 1) {
            if (isset($data['level'])) {
                admin::update(['status' => 0], ['level' => $data['level']]);
                $redis = new RedisUtil();
                $redis->set('userlevel'.$data['level'],$model->discount);
            } else {
                admin::update(['status' => 0], ['level' => $model->level]);
            }
        }
        if (!empty($data['content_id'])){
            $content_id = $data['content_id'];
            unset($data['content_id']);
        }
        foreach($content_id AS $key => $value){
            $array[] = ['mid' => $id,'cid' => $value];
        }
        $count = admin::where('level',$data['level'])->where('id','<>',$id)->count();
        if ($count > 0)
            throw new Exception('已经存在该等级的数据',HTTP_NOTACCEPT);
        $relation = new MembershipLevelContentRelation();
        $relation->where('mid',$id)->delete();
        !empty($array) && $relation->insertAll($array);
        $admin = admin::update($data,['id'=>$id]);

        return [HTTP_CREATED, $admin];
    }

    /**
     * @param $id
     * @return int
     */
    public function delete($id)
    {
        admin::destroy($id);
        return HTTP_NOCONTEND;
    }


    public function setUserLevel(int $user_id,int $level,?string $level_time,string $password) : int {

        global $user;
        if($user->affiliation == 'saas') {
            $admin = Db::name('saas_admin')->where('id', $user->id)->find();
        }else if($user->affiliation == 'suser') {
            $admin = Db::name('saas_user')->where('id', $user->id)->find();
        }else{
            $admin = \app\madmin\model\Admin::where('status', 1)->where('id', $user->id)->find()->toArray();
        }

        if (!$admin || hash('sha256', $password) != $admin['password']){

            throw new \Exception("密码错误", HTTP_NOTACCEPT);

        }

        $id = admin::where('level',$level)
            ->where('status',1)
            ->value('id');
        if (empty($id) && $level != 0)throw new Exception('等级不存在',HTTP_NOTACCEPT);
        $user = User::find($user_id);
        $user->save(['level' => $level,'level_time' => empty($level_time) ? null : $level_time]);
        return HTTP_SUCCESS;
    }


    /**
     * 说明列表
     * @param int $page
     * @param int $size
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function contentList(int $page, int $size,array $post) : array{
        $where = [];
        if (!empty($post['is_open']))$where[] = ['is_open','=',$post['is_open']];
        $list = content::order('id DESC')
            ->paginate(['page' => $page,'size' => $size])
            ->toArray();
        return [HTTP_SUCCESS,$list];
    }

    /**
     * 说明详情
     * @param int $id
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function contentRead(int $id) : array{
        $data = content::find($id);
        return [HTTP_SUCCESS,$data];
    }

    /**
     * 说明添加
     * @param array $array
     * @return array
     * @throws Exception
     */
    public function contentSave(array $array) : array{
        $data = content::create($array);
        if ($data->isEmpty())
            throw new Exception('创建失败',HTTP_NOTACCEPT);
        return [HTTP_SUCCESS,$data];
    }

    /**
     *更新说明
     * @param int $id
     * @param array $array
     * @return array
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function contentUpdate(int $id, array $array) : array{
        $content = content::find($id);
        if ($content->isEmpty())
            throw new Exception('数据不存在',HTTP_NOTACCEPT);
        $content->save($array);
        return [HTTP_SUCCESS,$content];
    }

    /**
     * 删除说明
     * @param int $id
     * @return int
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function contentDelete(int $id) : int{
        $content = content::find($id);
        if ($content->isEmpty())
            throw new Exception('数据不存在',HTTP_NOTACCEPT);
        MembershipLevelContentRelation::where('cid',$id)->delete();
        $content->delete();
        return HTTP_SUCCESS;
    }
}
